import socket
import sys
import os
# 获取的地址
BASE_PATH = os.path.dirname(os.path.dirname(__file__))
sys.path.append(BASE_PATH)
from lib import common
from conf import settings

phone = socket.socket()
phone.bind(("127.0.0.1", 8080))
phone.listen(3)

while True:
    conn, addr = phone.accept()
    print(f"{addr}客户端连接了")

    while True:
        try:
            msg = ""
            obj = getattr(common, "Network")()
            for num, option in enumerate(obj.lst, 0):
                msg += f'{num + 1}: {option[0]}\n'
            conn.send(msg.encode("utf-8"))

            from_client_num = conn.recv(1024).decode("utf-8")

            if from_client_num == "1" or from_client_num == "2":
                from_client_napwd = conn.recv(1024).decode("utf-8")
                register = getattr(obj, obj.lst[int(from_client_num) - 1][1])(from_client_napwd)
                conn.send(register.encode("utf-8"))

            elif from_client_num == "3":
                type_in_c = b""
                file_in = conn.recv(1024).decode("utf-8")
                file_path_in = os.path.join(settings.UPLOAD_FILE_IN, file_in)
                with open(file_path_in, "ab")as f:
                    while True:
                        type_in = conn.recv(1024)
                        type_in_c += type_in
                        if len(type_in) < 1024:
                            break
                    f.write(type_in_c)
                conn.send("上传成功！".encode("utf-8"))

            elif from_client_num == "4":
                file_out_download = b""
                file_in_download = b""
                file_download = conn.recv(1024).decode("utf-8")
                file_server = os.path.join(settings.UPLOAD_FILE_IN, file_download)
                file_client = os.path.join(settings.UPLOAD_FILE_OUT, file_download)
                with open(file_server, "rb")as f2, open(file_client, "ab")as f3:
                    while 1:
                        type_a = f2.read(1024)
                        f3.write(type_a)
                        if not type_a:
                            break
                conn.send("下载完成！".encode("utf-8"))

        except Exception:
            print(f"{addr}客户端关闭了")
            break
    conn.close()

phone.close()